import { getStorageSync, setStorageSync, showToast } from "@tarojs/taro";
import { Axios, IAxiosOptions } from "./axios";
import env from "../utils/env"
import {IResponseData, SuccessCallbackResult} from "./types";
import { TOKEN, TRACE_Id } from "../utils/constants";

/********************************************************
 *            普通     请求       Start                  *
 ********************************************************/

export const axios: Axios = Axios.create({
  baseUrl: env.API_BASE_URL
})
axios.request((opt: IAxiosOptions) => {
  // 获取token
  let token: string | null = getStorageSync(TOKEN)|| null;
  // 获取去traceId
  let traceId: string | null = getStorageSync(TRACE_Id);
  // 组合token
  if (opt.needToken && token != null) {
    opt.header = { ...opt.header, "Authorization": 'Bearer ' + token };
  } else opt.header = {};
  if (traceId) opt.header["traceId"] = traceId

  return opt;
})
axios.response((res, opt: IAxiosOptions) => {
  const { simple } = opt;
  const data:IResponseData = res.data;
  const response: SuccessCallbackResult<any> | IResponseData = simple ? data : res;
  const { status, msg } = data;
  if (status === 0) {
    return Promise.resolve(response);
  } else if (status === -2 || status === -3 || status === 100) {
    setStorageSync(TOKEN, null)
    if (opt.showError)
      showToast({
        title: msg,
        icon: "error",
        duration: 3000
      })
  } else {
    if (opt.showError)
      showToast({
        title: msg,
        icon: "error",
        duration: 3000
      })
  }
  if (res.data.data.traceId) {
    setStorageSync(TRACE_Id, res.data.data.traceId)
  }
  return Promise.reject(response);
})
/********************************************************
 *            普通请求            End                    *
 ********************************************************/
